import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_libserialport/flutter_libserialport.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:yun/page/log_page.dart';

import '../entity/setting_entity.dart';
import '../event/change_mode_event.dart';
import '../event/inventory_event.dart';
import '../event/read_block_event.dart';
import '../event/voice_change_event.dart';
import '../main.dart';
import '../mqtt/mqtt.dart';
import '../serial/inventory_manager.dart';
import '../serial/send_helper.dart';
import '../util/toast_util.dart';

class SettingCommon extends StatefulWidget {
  const SettingCommon({Key? key}) : super(key: key);

  @override
  State<SettingCommon> createState() => _SettingCommonState();
}

class _SettingCommonState extends State<SettingCommon>  {

  StreamSubscription? actionSubscription;
  StreamSubscription? readBlockSubscription;
  SettingEntity? entity;
  final box = GetStorage();
  var _deviceNo = "HF01010101";
  var _region = "lishui";
  final _hfSerial = '/dev/ttyS2'.obs;
  final _log = false.obs;

  List<String> rfidList = [];
  List<String> blocks = [];
  InventoryManager inventoryManager = InventoryManager();


  @override
  initState() {
    super.initState();

    if(box.hasData('setting_entity')){
      entity = SettingEntity.fromJson(box.read("setting_entity"));
      _init();
    }else{
      entity = SettingEntity();
    }

    readBlockSubscription = eventFactory.on<ReadBlockEvent>().listen((event) async {
      var rfid = event.data.$1;
      var no = event.data.$2;
      if(rfid != null){
        blocks.add('$rfid--$no');
      }else{
        var msg = '';
        for (var element in blocks) {
          msg += '$element\n';
        }
        Get.defaultDialog(
          title: '读到${blocks.length}条数据',
          titleStyle: TextStyle(
            color: const Color(0xFF000000),
            fontSize: 8.sp,
          ),
          middleText: msg,
          middleTextStyle: TextStyle(
            color: const Color(0xFF000000),
            fontSize: 6.sp,
          ),
          radius: 8.sp,
          textConfirm: '确定',
          // textCancel: '取消',
          confirmTextColor: const Color(0xFF007AFF),
          backgroundColor: const Color(0xD1F8F8F8),
          buttonColor: Colors.transparent,
          onConfirm: () {
            Get.back();
          },
        );
      }
    });

    actionSubscription = eventFactory.on<InventoryEvent>().listen((event) {
      rfidList.clear();
      rfidList.addAll(event.data.map((e) => e));
      Get.defaultDialog(
        title: '盘点完成',
        titleStyle: TextStyle(
          color: const Color(0xFF000000),
          fontSize: 8.sp,
        ),
        middleText: '盘点到${event.data.length}个标签',
        middleTextStyle: TextStyle(
          color: const Color(0xFF000000),
          fontSize: 8.sp,
        ),
        radius: 8.sp,
        textConfirm: '确定',
        // textCancel: '取消',
        confirmTextColor: const Color(0xFF007AFF),
        backgroundColor: const Color(0xD1F8F8F8),
        buttonColor: Colors.transparent,
        onConfirm: () {
          Get.back();
        },
      );
    });
  }

  _init(){
    if(entity!.deviceNo != null){
      _deviceNo = entity!.deviceNo!;
    }
    if(entity!.hfSerial != null){
      _hfSerial.value = entity!.hfSerial!;
    }
    if(entity!.log != null){
      _log.value = entity!.log!;
    }
    if(entity!.region != null){
      _region = entity!.region!;
    }
  }

  @override
  void dispose() {
    actionSubscription?.cancel();
    actionSubscription = null;
    readBlockSubscription?.cancel();
    readBlockSubscription = null;
    super.dispose();
  }


  _serialWidget(){
    List<String> availablePorts = SerialPort.availablePorts;
    var items = availablePorts.map((e) => DropdownMenuItem(value:e, child:Text(e))).toList();
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  读写器  ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _hfSerial.value,
            onChanged: (value){
              _hfSerial.value = value.toString();
            },
            items: items,
          )),
        ),
      ],
    );
  }

  _deviceNameWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  设备号",   style: TextStyle(fontSize: 8.sp)),
        Container(
          width: 150.w,
          height: 40.h,
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _deviceNo = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _deviceNo,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _deviceNo.length))
            )),
          ),
        ),
        TextButton(onPressed: () {
          _saveDevice();
        }, child: Text('保存配置', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          Get.defaultDialog(
            title: '退出',
            titleStyle: TextStyle(
              color: const Color(0xFF000000),
              fontSize: 10.sp,
            ),
            middleText: '确定退出应用？',
            middleTextStyle: TextStyle(
              color: const Color(0xFF000000),
              fontSize: 8.sp,
            ),
            radius: 4.sp,
            textConfirm: '确定',
            // textCancel: '取消',
            confirmTextColor: const Color(0xFF007AFF),
            backgroundColor: const Color(0xD1F8F8F8),
            buttonColor: Colors.transparent,
            onConfirm: () async {
              await const MethodChannel('toAndroid').invokeMethod('showBar');
              SystemNavigator.pop();
              exit(0);
            },
          );
        }, child: Text('退出', style: TextStyle(fontSize: 8.sp))),

        // TextButton(onPressed: () {
        //   Get.to(()=>const Log());
        // }, child: Text('查看日志', style: TextStyle(fontSize: 8.sp))),
      ],
    );
  }
 _regionWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  地区",   style: TextStyle(fontSize: 8.sp)),
        Container(
          width: 100.w,
          height: 40.h,
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _region = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _region,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _region.length))
            )),
          ),
        ),

        Text("    视频播放日志",style: TextStyle(fontSize: 8.sp),),
        Obx(() => Checkbox(
            side: MaterialStateBorderSide.resolveWith((Set<MaterialState> states) {
              return const BorderSide(width: 2);
            }),
            value: _log.value,
            onChanged: (value){
              _log.value = !_log.value;
            }
        )),
      ],
    );
  }

  _testWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [

        TextButton(onPressed: () {
          inventoryManager.startInventory(settingEntity.count??4);

        }, child: Text('盘点', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          if(rfidList.isEmpty){
            toastWarn('请先盘点');
            return;
          }
          blocks.clear();
          inventoryManager.addRfids(rfidList);
        }, child: Text('读块', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          hfSerialPortHelper.sendData(openDoor());
        }, child: Text('开门', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          hfSerialPortHelper.sendData(openLight());
        }, child: Text('开灯1', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          hfSerialPortHelper.sendData(closeLight());
        }, child: Text('关灯1', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          hfSerialPortHelper.sendData(openLight2());
        }, child: Text('开灯2', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          hfSerialPortHelper.sendData(closeLight2());
        }, child: Text('关灯2', style: TextStyle(fontSize: 8.sp))),
        // TextButton(onPressed: () {
        //   HttpHelper.instance.downLoadApk('https://h5-1252616249.cos.ap-shanghai.myqcloud.com/1.1.0.apk');
        //
        // }, child: Text('测试升级', style: TextStyle(fontSize: 8.sp))),
        // TextButton(onPressed: () {
        //   HttpHelper.instance.downLoad('https://h5-1252616249.cos.ap-shanghai.myqcloud.com/1.1.0.apk');
        //
        // }, child: Text('测试音频下载', style: TextStyle(fontSize: 8.sp))),

        TextButton(onPressed: () async {
          eventFactory.fire(VoiceChangeEvent(0));
          tts.speak('测试测试测试测试');
        }, child: Text('音频测试', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () async {
          settingEntity.mode = 1;
          settingEntity.url = 'https://www.baidu.com';
          final box = GetStorage();
          box.write('setting_entity', settingEntity.toJson());
          eventFactory.fire(ChangeModeEvent());
        }, child: Text('切换h5', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () async {
          settingEntity.mode = 0;
          final box = GetStorage();
          box.write('setting_entity', settingEntity.toJson());
          eventFactory.fire(ChangeModeEvent());
        }, child: Text('切换广告', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () async {
          await const MethodChannel('toAndroid').invokeMethod('restart');
        }, child: Text('重启', style: TextStyle(fontSize: 8.sp))),

        // TextButton(onPressed: () async {
        //   await const MethodChannel('toAndroid').invokeMethod('initCardReader');
        // }, child: Text('initReader', style: TextStyle(fontSize: 8.sp))),
        // TextButton(onPressed: () async {
        //   await const MethodChannel('toAndroid').invokeMethod('releaseCardReader');
        // }, child: Text('releaseReader', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () async {
          Get.to(()=>const Log());
        }, child: Text('日志', style: TextStyle(fontSize: 8.sp))),
      ],
    );
  }


  _saveDevice(){
    entity!.deviceNo = _deviceNo;
    entity!.region = _region;
    entity!.hfSerial = _hfSerial.value;
    entity!.log = _log.value;
    box.write('setting_entity', entity!.toJson());

    toastWarn('保存成功');
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child:Scaffold(
          resizeToAvoidBottomInset: false,
          appBar: AppBar(
            title: const Text("配置"),
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios),
              onPressed: (){
                if(box.hasData('setting_entity')){
                  settingEntity = SettingEntity.fromJson(box.read("setting_entity"));
                }
                Get.back();
              },
            ),
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _deviceNameWidget(),
              _regionWidget(),
              _serialWidget(),
              _testWidget(),
              // _test2Widget(),
              Text('  版本号：$currentVersion'),
            ],
          )
      ),
    );
  }
}

